package com.forester.foresterplatform.common.mp;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.forester.foresterplatform.common.utils.SecurityUtils;
import com.forester.foresterplatform.system.entity.User;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Optional;

@Component
public class BaseEntityMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Optional<User> loginedUser = SecurityUtils.getLoginedUser();
        metaObject.setValue("createdBy", loginedUser.map(User::getId).orElse(null));
        metaObject.setValue("updatedBy", loginedUser.map(User::getId).orElse(null));
        metaObject.setValue("createdTime", LocalDateTime.now());
        metaObject.setValue("updatedTime", LocalDateTime.now());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Optional<User> loginedUser = SecurityUtils.getLoginedUser();
        metaObject.setValue("updatedBy", loginedUser.map(User::getId).orElse(null));
        metaObject.setValue("updatedTime", LocalDateTime.now());
    }
}
